package com.partsoft.spring.support;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

import com.partsoft.dits.dsm.DefaultContextDataSourceManager;
import com.partsoft.spring.log.Log;
import com.partsoft.utils.Assert;

public class DataSourceFactoryBeanDefinitionParaser implements BeanDefinitionParser {
	
	public static final String ElementName = "datasource-factory";
	
	public static final String DefaultDataSourceFactoryID = "dataSourceFactory";

	public BeanDefinition parse(Element element, ParserContext parserContext) {
		Assert.notNull(element);
		Assert.notNull(parserContext);
		String id = element.hasAttribute("id") ? element.getAttribute("id") : DefaultDataSourceFactoryID;
		String config_location = element.hasAttribute("config") ? element.getAttribute("config") : null;
		Assert.hasText(config_location, String.format("Must be set config property for <%s> node", ElementName));
		String config_readonly = element.hasAttribute("readonly") ? element.getAttribute("readonly") : "false";
		BeanDefinitionBuilder dataSourceFactoryBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultContextDataSourceManager.class);
		dataSourceFactoryBuilder.addPropertyValue("contextProfileLocation", config_location);
		dataSourceFactoryBuilder.addPropertyValue("profileCanBeWrite", !"true".equalsIgnoreCase(config_readonly));
		dataSourceFactoryBuilder.addPropertyValue("createProfileNoExists", !"true".equalsIgnoreCase(config_readonly) && true);
		parserContext.getRegistry().registerBeanDefinition(id, dataSourceFactoryBuilder.getBeanDefinition());
		if (Log.isDebugEnabled()) {
			Log.debug(dataSourceFactoryBuilder.toString());
		}
		return null;
	}
}
